package com.tdrc.common.controller;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tdrc.common.beans.Audience;
import com.tdrc.common.beans.User;
import com.tdrc.common.service.UserService;
import com.tdrc.common.util.CommonUtil;
import com.tdrc.common.util.JsonResult;
import com.tdrc.common.beans.ResultCode;
import com.tdrc.common.util.JwtTokenUtil;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * @author dpf
 * @version 1.0
 * @date 2020-4-13 15:22
 * @instruction ...
 */
@RestController
@RequestMapping("/user")
public class UserController extends BaseController{
    @Resource
    private UserService userService;

    @Resource
    private Audience audience;
    @PostMapping("/login")
    public Object login(HttpServletResponse response, @RequestBody User logUser) {
        User user = userService.getUserByLogName(logUser.getLogName());
        if(user==null){
            return new JsonResult(ResultCode.USER_LOGIN_ERROR);
        }
        if(user.getStatus()==0){
            return new JsonResult(ResultCode.USER_ACCOUNT_FORBIDDEN);
        }
        if (user.getPassword().equals(logUser.getPassword())) {
            String token = JwtTokenUtil.createJWT(user.getUserId().toString(), logUser.getPassword(), null, audience);
            String access_token = "Bearer "+token;
            user.setToken(access_token);
            response.setHeader(JwtTokenUtil.ACCESS_TOKEN, "Bearer "+token);
            return new JsonResult(ResultCode.OK,user);
        } else {
            return new JsonResult(ResultCode.USER_LOGIN_ERROR);
        }
        // 将token响应给客户端

    }
    //@RequiresPermissions({"/user/listPageUser"})
    @GetMapping("/listPageUser")
    public Object listPageUser(Integer page,Integer pageSize,Integer unitId,String userName){
        Map<String,Object> map = new HashMap<String,Object>(16);
        map.put("unitId",unitId);
        map.put("userName",userName);
        PageHelper.startPage(page, pageSize);
        List<Map<String,Object>> data = userService.listPageUser(map);
        PageInfo<Map<String,Object>> pageInfo = new PageInfo<Map<String,Object>>(data);
        return new JsonResult(ResultCode.OK,pageInfo.getList(),pageInfo.getTotal());
    }
    @PostMapping("/add")
    public Object add(@RequestBody User user){
        if(ResultCode.USER_NAME_NOT_UNIQUE.getVal()==userService.checkUserNameUnique(user.getUserName())){
            return new JsonResult(ResultCode.USER_NAME_NOT_UNIQUE);
        }
        if(ResultCode.USER_LOG_NAME_NOT_UNIQUE.getVal()==userService.checkLogNameUnique(user.getLogName())){
            return new JsonResult(ResultCode.USER_LOG_NAME_NOT_UNIQUE);
        }
        user.setCreateTime(CommonUtil.getNowDateTime());
        user.setStatus(1);
        userService.addUser(user);
        return new JsonResult(ResultCode.OK);
    }
    @PostMapping("/update")
    public Object update(@RequestBody User user){
        userService.updateUser(user);
        return new JsonResult(ResultCode.OK);
    }
    @DeleteMapping("/delete/{userId}")
    @Transactional(rollbackFor = Exception.class)
    public Object delete(@PathVariable Integer userId){
        userService.deleteUserRoleByUserId(userId);
        userService.deleteUser(userId);
        return new JsonResult(ResultCode.OK);
    }
    @PostMapping("/updateStatus")
    public Object updateStatus(@RequestBody User user){
        userService.updateUserStatus(user);
        return new JsonResult(ResultCode.OK);
    }

    /**
     * 根据用户ID获取带状态的角色
     * @param userId
     * @return
     */
    @GetMapping("/getRoleList/{userId}")
    public Object getRoleList(@PathVariable Integer userId){
        return new JsonResult(ResultCode.OK,userService.getRoleList(userId));
    }
    /**
     * 根据用户ID配置角色
     */
    @PostMapping("/configRole")
    @Transactional(rollbackFor = Exception.class)
    public Object  configRole(Integer userId,String roles){
        userService.deleteUserRoleByUserId(userId);
        if(!StringUtils.isEmpty(roles) ){
               String[] rolesArr = roles.split(",");
               List<Integer> list = new ArrayList<Integer>();
               for(int i=0,len=rolesArr.length;i<len;i++){
                   list.add(Integer.parseInt(rolesArr[i]));
               }
               userService.addUserRole(list,userId);
        }
        return new JsonResult(ResultCode.OK);
    }
    @GetMapping("/userInfo")
    public Object userInfo(Integer userId){
        userService.getUserInfo(userId);
        String json = "{\n" +
                "    'id': '4291d7da9005377ec9aec4a71ea837f',\n" +
                "    'name': '天野远子',\n" +
                "    'username': 'admin',\n" +
                "    'password': '',\n" +
                "    'avatar': '/avatar2.jpg',\n" +
                "    'status': 1,\n" +
                "    'role': {\n" +
                "      'permissions': [{\n" +
                "        'roleId': '1',\n" +
                "        'permissionId': 'menu',\n" +
                "        'roleName': '菜单管理',\n" +
                "        'actionEntitySet': [\n" +
                "          {\n" +
                "            'action': 'add',\n" +
                "            'describe': '新增',\n" +
                "          },\n" +
                "          {\n" +
                "            'action': 'import',\n" +
                "            'describe': '导入',\n" +
                "          }, {\n" +
                "            'action': 'get',\n" +
                "            'describe': '详情',\n" +
                "          }, {\n" +
                "            'action': 'update',\n" +
                "            'describe': '修改',\n" +
                "          }, {\n" +
                "            'action': 'delete',\n" +
                "            'describe': '删除',\n" +
                "          }, {\n" +
                "            'action': 'export',\n" +
                "            'describe': '导出',\n" +
                "          }],\n" +
                "      }]\n" +
                "\n" +
                "\n" +
                "    }\n" +
                "  }";
        JSON js = JSON.parseObject(json);
        return new JsonResult(ResultCode.OK,userService.getUserInfo(userId));
    }
}
